/***********************************************
 This file is part of redia-lib-utils-ios
.
 
 Copyright (c) 2012, 2013 Redia A/S
 
 Redia-library-app-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-library-app-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-library-app-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */


#import "UrlCacheImageEntry.h"
#import "UrlCacheManager.h"
#import "defines.h"

@implementation UrlCacheImageEntry

- (BOOL)loadImageFromURL:(NSURL *)inURL delegate:(id<UrlCacheEntryDelegate>)finishedDelegate
{
	self.fetchFromUrl = inURL;
	self.delegate = finishedDelegate;
	
	NSURLRequest *request = [NSURLRequest requestWithURL:inURL];
    self.urlConnection = [NSURLConnection connectionWithRequest:request delegate:self];
	
    if (self.urlConnection) {
        asyncImageData = [NSMutableData data];
    } else {
        return FALSE;
    }
	
    return TRUE;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSLog(@"UrlCacheEntry load image error: %@",error);
    NSLog(@"error url: %@",self.fetchFromUrl);
	[self.delegate cacheEntry:self didFailOnUrl:self.fetchFromUrl error:error];
}

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response {
	if ([response respondsToSelector:@selector(statusCode)])
	{
		int statusCode = (int)[((NSHTTPURLResponse *)response) statusCode];
		if (statusCode >= 400)
		{
			[conn cancel];  // stop connecting; no more delegate messages
			NSDictionary *errorInfo
			= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:
												  NSLocalizedString(@"Server returned status code %d",@""),
												  statusCode]
										  forKey:NSLocalizedDescriptionKey];
			NSError *statusError
			= [NSError errorWithDomain:NSURLErrorDomain
								  code:statusCode
							  userInfo:errorInfo];
			[self connection:conn didFailWithError:statusError];
		}
	} else {
		[asyncImageData setLength:0]; 
	}

}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data {
    [asyncImageData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
    // do something with the data
    DLog(@"UrlCacheEntry image load received %d bytes of data", (int)[asyncImageData length]);
	
	self.resultImage = [[UIImage alloc] initWithData:asyncImageData];
	
    if (self.resultImage!=nil) {
        //only insert into cache if we know that it is a valid image
        [[UrlCacheManager instance] saveImage:asyncImageData fromUrl:self.fetchFromUrl imageWidth:self.resultImage.size.width imageHeight:self.resultImage.size.height];
	}
	
    if (self.resultImage!=nil) {
        [self.delegate cacheEntry:self didLoadObjectFromUrl:self.fetchFromUrl ofType:UrlCacheEntryTypeImage]; //the delegate must retain the UIImage
    } else {
        [self.delegate cacheEntry:self didFailOnUrl:self.fetchFromUrl error:[NSError errorWithDomain:@"UrlCacheManger" code:301 userInfo:@{NSLocalizedDescriptionKey: @"not valid image file"}]];
    }
}


@end
